import { Injectable, HttpException, HttpStatus } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { User } from '../entities/user.entity'
import { CreateUserDto } from '../dto/create-user.dto'
import { UpdateUserDto } from '../dto/update-user.dto'

/**
 * 用户服务
 * 提供用户相关的业务逻辑
 */
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepo: Repository<User>,
  ) {}

  /**
   * 创建用户
   * @param createUserDto 创建用户数据
   */
  async create(createUserDto: CreateUserDto): Promise<User> {
    // 检查用户名是否已存在
    const existUser = await this.userRepo.findOne({
      where: [{ username: createUserDto.username }, { email: createUserDto.email }],
    })
    if (existUser) {
      throw new HttpException('用户名或邮箱已存在', HttpStatus.BAD_REQUEST)
    }

    // 创建用户
    const user = this.userRepo.create(createUserDto)
    return this.userRepo.save(user)
  }

  /**
   * 获取所有用户列表
   * @param page 页码
   * @param limit 每页数量
   */
  async findAll(page: number = 1, limit: number = 10): Promise<{ data: User[]; total: number }> {
    const [data, total] = await this.userRepo.findAndCount({
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' },
    })

    return { data, total }
  }

  /**
   * 根据ID获取用户详情
   * @param id 用户ID
   */
  async findOne(id: number): Promise<User> {
    const user = await this.userRepo.findOne({ where: { id } })
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
    }
    return user
  }

  /**
   * 根据用户名获取用户
   * @param username 用户名
   */
  async findByUsername(username: string): Promise<User | null> {
    return this.userRepo.findOne({ where: { username } })
  }

  /**
   * 根据邮箱获取用户
   * @param email 邮箱
   */
  async findByEmail(email: string): Promise<User | null> {
    return this.userRepo.findOne({ where: { email } })
  }

  /**
   * 更新用户信息
   * @param id 用户ID
   * @param updateUserDto 更新数据
   */
  async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
    const user = await this.findOne(id)

    // 如果更新用户名或邮箱，检查是否重复
    if (updateUserDto.username || updateUserDto.email) {
      const existUser = await this.userRepo.findOne({
        where: [{ username: updateUserDto.username || user.username }, { email: updateUserDto.email || user.email }],
      })
      if (existUser && existUser.id !== id) {
        throw new HttpException('用户名或邮箱已存在', HttpStatus.BAD_REQUEST)
      }
    }

    // 更新用户信息
    Object.assign(user, updateUserDto)
    return this.userRepo.save(user)
  }

  /**
   * 删除用户
   * @param id 用户ID
   */
  async remove(id: number): Promise<void> {
    const user = await this.findOne(id)
    await this.userRepo.remove(user)
  }

  /**
   * 更新用户状态
   * @param id 用户ID
   * @param status 状态（1: 启用, 0: 禁用）
   */
  async updateStatus(id: number, status: number): Promise<User> {
    const user = await this.findOne(id)
    user.status = status
    return this.userRepo.save(user)
  }

  /**
   * 更新最后登录时间
   * @param id 用户ID
   */
  async updateLastLogin(id: string): Promise<void> {
    await this.userRepo.update(id, { lastLoginAt: new Date() })
  }
}
